package reaction.utils.xml;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

public class XmlTest {

 public static void main(String[] args) throws Exception {
  String xmlString = "<tag><nested>hello</nested></tag>";
  DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

  InputStream inputStream = new ByteArrayInputStream(xmlString.getBytes());
  Document document = documentBuilder.parse(inputStream);

  XmlTest xmlTest = new XmlTest();
  xmlTest.serialize(document, System.out);

 }

 public void serialize(Document doc, OutputStream out) throws Exception {

  TransformerFactory tfactory = TransformerFactory.newInstance();
  Transformer serializer;
  try {
   serializer = tfactory.newTransformer();
   //Setup indenting to "pretty print"
   serializer.setOutputProperty(OutputKeys.INDENT, "yes");
   serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

   DOMSource xmlSource = new DOMSource(doc);
   StreamResult outputTarget = new StreamResult(out);
   serializer.transform(xmlSource, outputTarget);
  } catch (TransformerException e) {
   // this is fatal, just dump the stack and throw a runtime exception
   e.printStackTrace();

   throw new RuntimeException(e);
  }
 }
}
